package com.yoda.youdianda.controller;

import com.yoda.youdianda.common.ErrorResult;
import com.yoda.youdianda.common.R;
import com.yoda.youdianda.common.RC;
import com.yoda.youdianda.common.ThreadContext;
import com.yoda.youdianda.exception.BusinessException;
import com.yoda.youdianda.vo.ImageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${youdianda.backPath}")
    private String backPath;
    @Value("${youdianda.frontPath}")
    private String frontPath;

    @PostMapping("/upload")
    public R<ImageVo> upload(HttpSession session, MultipartFile file) {

        String originalFilename = file.getOriginalFilename();
        //扩展名获取
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //文件名获取
        String fileName = UUID.randomUUID() + suffix;
        //相对路径配置
        String property = System.getProperty("user.dir");//获取系统路径前缀
        String backId = ThreadContext.getId(RC.SYS_ID);
        String imgDir ;
        if (Objects.isNull(backId)){
             imgDir = property + frontPath;
        }else {
             imgDir = property + backPath;
        }


        //获取瑞对象
        File file1 = new File(imgDir);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        //savePath拼凑
        String imgPath = imgDir +"/"+ fileName;

        //session域存储,用于添加
        session.setAttribute("imgName", imgPath);

        try {
            //文件存储
            file.transferTo(new File(file1 ,fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //睡眠一秒,前端图片一闪而过,完美模仿黑马优点达
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //获取mimeType
        String mime = "";
        Optional<MediaType> mediaType = MediaTypeFactory.getMediaType(originalFilename);
        if(mediaType.isPresent()){
            mime=mediaType.get().toString();
        }

        ImageVo imageVo = new ImageVo("upload/images/"+fileName, originalFilename, mime, file.getSize());
        return R.success(imageVo);
    }
}